package com.lanou.bbs.dao;

import com.lanou.bbs.entity.User;
import com.lanou.bbs.util.JDBCUtil;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@Repository
public class UserDao {
    public User findByUsername(String username) throws SQLException {
        Connection connection = JDBCUtil.getConnection();//获取连接
        String sql ="select * from user where username=?";//查询数据库
        PreparedStatement ps = connection.prepareStatement(sql);//拿到预编译的statement
        ps.setString(1,username);
        ResultSet rs = ps.executeQuery();
        if (rs.next()){
            User user=new User();
            user.setUser_id(rs.getInt("user_id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setHead(rs.getString("head"));
            user.setGender(rs.getString("gender"));
            user.setReg_time(rs.getDate("reg_time"));
            connection.close();
            return user;

        }else {
            connection.close();
            return null;
        }
    }
    public void add(User user) throws SQLException {
        Connection connection=JDBCUtil.getConnection();
        String sql ="insert into user(username,password,head,reg_time,gender values(?,?,?,?,?)";
        PreparedStatement ps=connection.prepareStatement(sql);
        ps.setString(1,user.getUsername());
        ps.setString(2,user.getPassword());
        ps.setString(3,user.getHead());
        ps.setDate(4,null);
        ps.setString(5,user.getGender());
        ps.executeUpdate();
        connection.close();

    }
}
